/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package classcreator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Vector;

/**
 *
 * @author Stefano
 */
public class Method {
    private static double outputFormatVersion=1.0;
    
    public MethodHeader header;
    public Vector<String> body=new Vector<String>();
    
    public Method(MethodHeader h){
        header=h;
    }
    
    public void addBodyLine(String s){
        body.add(s);
    }
    
    public String toString(){
        
        String s=header.toString();
        s=s+"{"+"\n";
        if(!header.returnType.equals(Naming.voidType)&&!header.returnType.equals(Naming.constructorType)){
            s=s+Naming.tab+header.returnType.toString()+" "+Naming.standardReturnName+";\n";
        }
        for(String line:body){
            s=s+Naming.tab+line+"\n";
        }
        if(!header.returnType.equals(Naming.voidType)&&!header.returnType.equals(Naming.constructorType)){
            s=s+Naming.tab+"return "+Naming.standardReturnName+";\n";
        }
        s=s+"}";
        return s;
    }
    
    public static Method parse(BufferedReader br, TypeRepository tr) throws IOException{
                br.readLine();
                double version=Double.parseDouble(br.readLine());
                
                if(version<=1.0){
                    MethodHeader mh=MethodHeader.parse(br, tr);
                    int n=Integer.parseInt(br.readLine());
                    Method m=new Method(mh);
                    for(int i=0; i<n; i++){
                        m.addBodyLine(br.readLine());
                    }
                    return m;
                }
                //Actual version
                MethodHeader mh=MethodHeader.parse(br, tr);
                int n=Integer.parseInt(br.readLine());
                Method m=new Method(mh);
                for(int i=0; i<n; i++){
                    m.addBodyLine(br.readLine());
                }
                return m;
    }
    
    public void permanentize(BufferedWriter br, TypeRepository tr) throws IOException{
        br.write("/***/ Method: "+header.toString()); br.newLine();
        br.write(String.valueOf(outputFormatVersion)); br.newLine();
                header.permanentize(br,tr);
                br.write(String.valueOf(body.size())); br.newLine();
                for(String s:body){
                    br.write(s); br.newLine();
                }
    }
}
